<?php
namespace app\mall\logic;

use app\data\model\DataUser;
use app\data\service\MessageService;
use app\data\service\UserAdminService;
use think\facade\Db;
use think\facade\Log;

class loginLogic{

    /**
     * 验证手机号
     * @param string $phone
     * @return bool
     */
    public static function verification_phone(string $phone):bool{
        if(preg_match("/^1[34578]\d{9}$/", $phone)){
            return true;
        }
        return false;
    }

    /**
     * 发送短信
     * @param string $phone 手机号
     * @param string $code 验证码
     */
    public static function send_sms(string $phone ,string $code){
        return true;
    }

    /**
     * 发送短信验证码
     * @param string $phone
     * @return array
     */
    public static function phone_sms(string $phone):array
    {
        $is_phone = self::verification_phone($phone);
        if (!$is_phone) {
            return ['code' => 500, 'msg' => '手机号格式不正确'];
        }
        $code = rand(100000, 999999);
        [$res, $message] = MessageService::instance()->sendVerifyCode($phone);
        if ($res !== 1) {
            return ['code' => 500, 'msg' => $message];
        }
        // 缓存在300秒之后过期
        cache($phone, $code, 300);

        return ['code' => 200, 'msg' => '短信发送成功，5分钟内有效' . $code];
    }

    /**
     * 手机号注册
     * @param string $phone 手机号
     * @param string $password 密码
     * @param string $re_password 重复密码
     * @param string $code 验证码
     * @param string $p_phone 拉新上级手机号
     *
     * @return array
     * @throws \think\admin\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function phone_register(string $phone, string $password, string $re_password, string $code, string $p_phone): array
    {
        if (!empty($p_phone)) {
            Log::info('拉新手机号 - ' . $p_phone);
        }

        $is_phone = self::verification_phone($phone);
        if (!$is_phone) {
            return ['code' => 500, 'msg' => '手机号格式不正确'];
        }

        $checkResult = MessageService::instance()->checkVerifyCode($code, $phone);
        if (!$checkResult) {
            return ['code' => 500, 'msg' => '验证码无效！'];
        }

        $commomLogic = new commonLogic();
        $is_password = $commomLogic->ispwd($password, 1);
        if (!$is_password) {
            return ['code' => 500, 'msg' => '登录密码6-12位'];
        }
        if ($password != $re_password) {
            return ['code' => 500, 'msg' => '两次密码不一致'];
        }

        $is_register = Db::table('data_user')
            ->where('phone', '=', $phone)
            ->find();

        if ($is_register) {
            return ['code' => 500, 'msg' => '手机号已注册'];
        }
        $p_user = NULL;
        if ($p_phone) {
            $p_user = Db::table('data_user')->where('phone', '=', $p_phone)->find();
            if (!$p_user) {
                return ['code' => 500, 'msg' => '拉新用户不存在'];
            }
        }
        $data = [
            'nickname'     => '用户' . substr($phone, -4),
            //            'headimg' => 'https://pic3.zhimg.com/80/v2-911318ac58f4d15608e6b20a94834c3a_720w.webp',
            'headimg'      => request()->domain() . '/avatar.png',
            'password'     => md5($password),
            'pay_password' => md5($phone.$password),
            'phone'        => $phone,
            'pid1'         => isset($p_user) ? $p_user['id'] : 0,
        ];
        Db::startTrans();
        $res  = Db::table('data_user')->insertGetId($data);
        $res1 = Db::table('one_user_wallet')->insert(['u_id' => $res]);
        //有上一级，返积分
        if ($p_user) {
            //积分返还
            $invite_register_integral = sysdata('invite_register_integral');//拉新注册返积分
            walletLogic::wallet_detailed_add($p_user['id'], $invite_register_integral, 8, 2, 0, 'add', '拉新注册返积分');//增加记录
            Db::table('one_user_wallet')->where('u_id', '=', $p_user['id'])->inc('integral', $invite_register_integral)->update();//增加余额
        }
        if ($res && $res1) {
            Db::commit();
            return ['code' => 200, 'msg' => '注册成功'];
        }
        Db::rollback();

        return ['code' => 500, 'msg' => '注册失败'];
    }

    /**
     * 登录
     * @param string $phone 手机号
     * @param string $password 密码
     * @return array
     */
    public function login(string $phone, string $password, string $code): array
    {
        $is_phone = self::verification_phone($phone);
        if (!$is_phone) {
            return ['code' => 500, 'msg' => '手机号格式不正确', 'user_data' => []];
        }

//        $result = MessageService::instance()->checkVerifyCode($code, $phone);
//        if (!$result) {
//            return ['code' => 500, 'msg' => '手机验证码无效！', 'user_data' => []];
//        }

        $map  = ['deleted' => 0, 'phone' => $phone];
        $user = DataUser::mk()->where($map)->findOrEmpty();
        if ($user->isEmpty()) {
            return ['code' => 500, 'msg' => '该手机号还没有注册哦', 'user_data' => []];
        }

        if (empty($user['status'])) {
            return ['code' => 500, 'msg' => '该用户账号状态异常', 'user_data' => []];
        }

        if (md5($password) === $user['password']) {
            $user_data = UserAdminService::set($map, [], 'wap', TRUE);
            return ['code' => 200, 'msg' => '登录成功', 'user_data' => $user_data];
        }
        return ['code' => 500, 'msg' => '密码错误！', 'user_data' => []];
    }

}